package com.yungu.swift.api.wxapi;


import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.model.dto.PassengerLogDto;
import com.yungu.swift.assets.passenger.model.vo.PassengerVo;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonIdentifyDto;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.yungu.swift.api.config.NacosListener.SYS_CONFIG;

/**
 * Created by cuixiuyin on 2018/5/4.
 */
@Controller
@RequestMapping("/wx/passenger")
@Api(value = "【微信】乘客接口")
public class WxPassengerController {

    @Reference
    private PassengerService passengerService;
    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private OrderService orderService;

    @RequestMapping("/login/sendIdentifyCode")
    @ResponseBody
    @ApiOperation(value = "发送验证码", response = ResponseData.class, notes = "发送短信验证码接口")
    public ResponseData<Boolean> sendIdentifyCode(@ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile") String mobile,
                                                  HttpServletRequest request) {
        return commonSmsService.sendAliIdentify(mobile, WxConstants.APPID);
    }

    @RequestMapping("/login/validateOpenId")
    @ResponseBody
    @ApiOperation(value = "验证微信用户OpenID，如果有绑定账号获取订单状态", response = ResponseData.class, notes = "")
    public ResponseData<Map> validateOpenId(@ApiParam(name = "openId", value = "微信openid", required = true) @RequestParam(value = "openId") String openId, HttpServletRequest request) {
        Map resultMap = MapUtils.build(2);
        //查询是否在微信注册过
        Map<String, Object> map = MapUtils.build();
        map.put("openId", openId);
        PassengerDto passengerDto = passengerService.get(map).getData();
        //已经有绑定手机的情况，就返回用户信息，并且更新token
        if (StringUtils.isNotEmpty(openId) && passengerDto != null) {
            passengerDto.setToken(StringUtils.buildUUID());
            //图片已经拼接域名地址 不能直接更新回库
            passengerDto.setFace(null);
            //状态为激活
            passengerDto.setActive(1);
            passengerService.edit(passengerDto);
            resultMap.put("passengerDto", passengerDto);
            ResponseData<Map<String, Object>> responseData = orderService.getOrderStatus(passengerDto.getUuid(), null);
            if (responseData.isSuccess()) {
                resultMap.put("orderStatus", responseData.getData());
            }
            return ResponseData.buildSuccessResponse("存在绑定用户", resultMap);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "查无用户信息");
    }

    @RequestMapping("/unBind")
    @ResponseBody
    @ApiOperation(value = "微信解除绑定", response = ResponseData.class, notes = "")
    public ResponseData unBind(@ApiParam(name = "openId", value = "微信openid", required = true) @RequestParam(value = "openId") String openId, HttpServletRequest request) {
        Map<String, Object> map = MapUtils.build();
        map.put("openId", openId);
        PassengerDto passengerDto = passengerService.get(map).getData();
        //已经有绑定手机的情况，就返回用户信息，并且更新token
        if (passengerDto != null) {
            passengerDto.setOpenId("");
            //图片已经拼接域名地址 不能直接更新回库
            passengerDto.setFace(null);
            ResponseData responseData = passengerService.edit(passengerDto);
            if (responseData.isSuccess()) {
                return ResponseData.buildSuccessResponse("解除绑定成功", null);
            }
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "解除绑定失败");
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "查无用户信息");
    }

    @RequestMapping("/login")
    @ResponseBody
    @ApiOperation(value = "微信用户登录", response = ResponseData.class, notes = "APP存在的用户只更新APPID，不存在则新增，并返回用户信息给前台")
    public ResponseData login(@ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam(value = "mobile") String mobile,
                              @ApiParam(name = "nickName", value = "昵称", required = true) @RequestParam(value = "nickName", required = false) String nickName,
                              @ApiParam(name = "sex", value = "性别", required = true) @RequestParam(value = "sex") Integer sex,
                              @ApiParam(name = "identifyCode", value = "验证码", required = true) @RequestParam(value = "identifyCode") String identifyCode,
                              @ApiParam(name = "openId", value = "微信openid", required = true) @RequestParam(value = "openId") String openId,
                              HttpServletRequest request) {
        //校验验证码是否存在
        Map<String, Object> paramMap = MapUtils.build(16);
        CommonIdentifyDto identify = null;
        if (!MagicConstant.STRING_ONE_FOUR_TWO.equals(StringUtils.left(mobile, 3))) {
            paramMap.put("mobile", mobile);
            paramMap.put("identifyCode", identifyCode);
            paramMap.put("status", CommonConstant.IDENTIFY_CODE_STATUS_UNUSED);
            paramMap.put("appid", WxConstants.APPID);
            identify = commonSmsService.get(paramMap).getData();
        }
        if (!MagicConstant.STRING_ONE_FOUR_TWO.equals(StringUtils.left(mobile, 3)) && identify == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "验证码错误");
        }
        //查询是否存在该手机号用户
        Map<String, Object> map = MapUtils.build();
        map.put("mobile", mobile);
        PassengerDto passengerDto = passengerService.get(map).getData();
        //存在只更新
        if (passengerDto != null) {
            passengerDto.setOpenId(openId);
            //图片已经拼接域名地址 不能直接更新回库
            passengerDto.setFace(null);
            passengerService.edit(passengerDto);
        }
        //乘客新增
        if (passengerDto == null) {
            passengerDto = new PassengerDto();
            passengerDto.setMobile(mobile);
            if (nickName == null || nickName.length() > 32) {
                nickName = "微信用户";
            }
            passengerDto.setNickname(nickName);
            passengerDto.setSex(sex);
            passengerDto.setOpenId(openId);
            passengerDto.setAppid(SYS_CONFIG.getAppid());
        }
        ResponseData<PassengerVo> loginData = passengerService.login(passengerDto, new PassengerLogDto());
        if (loginData.isSuccess()) {
            //用户的验证码设置为已使用
            if (!MagicConstant.STRING_ONE_FOUR_TWO.equals(StringUtils.left(mobile, 3))) {
                identify.setStatus(CommonConstant.IDENTIFY_CODE_STATUS_USED);
                commonSmsService.edit(identify);
            }
            request.getSession().setAttribute("mobile", mobile);
            request.getSession().setAttribute("passengerUuid", passengerDto.getUuid());
        }
        return loginData;
    }
}
